package gs.sr.tkfxz.client;

import gs.sr.tkfxz.shared.FieldVerifier;
import gs.sr.tkfxz.shared.ReqParam;
import gs.sr.tkfxz.shared.TaokeItem;

import java.util.Map;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Tkfxz implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	private static final String default_input_text = "输入商品的网址";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final TaokeItemSearchAsync taokeItemSearch = GWT
			.create(TaokeItemSearch.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button sendButton = new Button("查一查");
		final TextBox urlField = new TextBox();
		urlField.addStyleName("inputl");
		urlField.setText(default_input_text);
		//
		// final TextBox nickField = new TextBox();
		// nickField.addStyleName("lst");
		// nickField.setText("输入用户名");
		final Label errorLabel = new Label();
		// final HTML hintLabel = new HTML();
		// hintLabel.setHTML("");

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(urlField);
		// RootPanel.get("nickFieldContainer").add(nickField);
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);
		// RootPanel.get("hintLabelContainer").add(hintLabel);

		// Focus the cursor on the name field when the app loads
		urlField.setFocus(true);
		urlField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("查询服务");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("关闭");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label itemUrlLabel = new Label();
		final Label userNickLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel
				.add(new HTML(
						"<b>返利账户（<a href=\"http://www.alimama.com/union/account/incomeDetail.htm\" target=\"_blank\">查看佣金</a>）：</b>"));
		dialogVPanel.add(userNickLabel);
		dialogVPanel.add(new HTML("<b>商品网址：</b>"));
		dialogVPanel.add(itemUrlLabel);
		dialogVPanel.add(new HTML("<br><b>查询结果：</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		class MiscHandler implements ClickHandler, BlurHandler {

			@Override
			public void onClick(ClickEvent event) {
				if (default_input_text.equals(urlField.getText())) {
					urlField.setText("");
					errorLabel.setText("");
					return;
				}

			}

			@Override
			public void onBlur(BlurEvent event) {
				String t = urlField.getText();
				if (t == null || t.trim().length() == 0) {
					urlField.setText(default_input_text);
					errorLabel.setText("");
					return;
				}

			}

		}

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}

			private boolean collectReqParam(ReqParam rp) {
				boolean b = false;
				/**
				 * app param
				 */
				// String userNick = nickField.getText();
				String itemUrl = urlField.getText();

				// rp.setUserNick(userNick);
				rp.setItemUrl(itemUrl);
				// top parameter
				rp.resetOtherParam(Window.Location.getParameterMap());

				b = true;

				return b;
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void sendNameToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				// collect param
				ReqParam rp = new ReqParam();
				if (!collectReqParam(rp)) {
					errorLabel.setText("参数有误，请从“我的淘宝”访问！");
					return;
				}
				// check param
				// if (!FieldVerifier.isValidUserNick(rp.getUserNick())) {
				// errorLabel.setText("请输入有效的返利账户");
				// return;
				// }
				if (!FieldVerifier.isValidItemUrl(rp.getItemUrl())) {
					errorLabel.setText("请输入有效的商品网址");
					return;
				}

				// Then, we send the input to the server.
				sendButton.setEnabled(false);

				itemUrlLabel.setText(rp.getItemUrl());
				serverResponseLabel.setText("");

				taokeItemSearch.search(rp, new AsyncCallback<TaokeItem>() {
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						dialogBox.setText("查询服务 - 失败");
						serverResponseLabel
								.addStyleName("serverResponseLabelError");
						if (false) {
							GWT.log("RPC - Failure", caught);
						}
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						closeButton.setFocus(true);
					}

					@Override
					public void onSuccess(TaokeItem result) {
						userNickLabel.setText(result.getRebateAccount());

						StringBuilder sb = new StringBuilder();
						dialogBox.setText("查询服务");
						serverResponseLabel
								.removeStyleName("serverResponseLabelError");
						sb.append(result.toString());
						serverResponseLabel.setHTML(sb.toString());
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		urlField.addKeyUpHandler(handler);

		MiscHandler miscHandler = new MiscHandler();
		urlField.addClickHandler(miscHandler);
		urlField.addBlurHandler(miscHandler);
	}

	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder(
				"<div id=\"abgneBlock\"><div id=\"player\"><ul class=\"list\">");
		for (Map.Entry<String, Long> entry : FieldVerifier
				.getSupporteditemurlmap().entrySet()) {
			String curl = entry.getKey() + "id=" + entry.getValue();
			sb.append("<li><a target=\"_blank\" href=\"").append(curl)
					.append("\">").append(curl).append("</a></li>");
		}
		sb.append("</ul></div></div>");

		System.err.println(sb.toString());
	}
}
